package com.scw.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;



import com.scw.model.SysUser;
import com.scw.service.UserService;
import com.scw.util.CommonNameUtil;


public class LoginFilter extends HttpServlet implements Filter {
	private String expUrl;//例外url
	private UserService userService;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) res;
		HttpSession session=request.getSession();
		session.setAttribute(CommonNameUtil.ROOT, request.getContextPath());
		SysUser user=(SysUser) request.getSession().getAttribute(CommonNameUtil.SessionUser);
		String url=request.getRequestURL().toString();
		String query=request.getQueryString();
		url=query==null?url:url+"?"+request.getQueryString();
		boolean exception=expUrl.indexOf(request.getServletPath())>-1;
		//有登陆或者是例外url可以直接过去
		if(user !=null || exception){
			chain.doFilter(req, res);
		}else{
			//没有登陆，试着进行自动登陆
			//自动登陆
			Cookie[] cookies=request.getCookies();
			if(cookies!=null){
				for(Cookie c:  cookies){
					SysUser sysuser=new SysUser();
					if("autologin".equals(c.getName())){
					sysuser.setUser_name(c.getValue().split(":")[0]);
					sysuser.setPassword(c.getValue().split(":")[1]);
					user=userService.login(sysuser);
					session.setAttribute(CommonNameUtil.SessionUser, user);
					CommonNameUtil.onlineList.put(user.getUser_name(), user);
					}
				}
			}
			//自动登陆成功，进行下一步
			if(user !=null || exception){
				chain.doFilter(req, res);
			}else{
				if(!exception)
					request.getSession().setAttribute(CommonNameUtil.sessionNextAction,url);
				response.sendRedirect(request.getContextPath()+"/login.jsp");
			}
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		expUrl=arg0.getInitParameter("expUrl");
	}

	public String getExpUrl() {
		return expUrl;
	}

	public void setExpUrl(String expUrl) {
		this.expUrl = expUrl;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

		
}
